package game.module.item.dao;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;

import game.module.template.ItemTemplate;
import lion.common.Reloadable;

public class ItemTemplateCache implements Reloadable {

	private static Logger logger = LoggerFactory.getLogger(ItemTemplateCache.class);

	static class SingletonHolder {
		static ItemTemplateCache instance = new ItemTemplateCache();
	}

	public static ItemTemplateCache getInstance() {
		return SingletonHolder.instance;
	}

	private transient List<ItemTemplate> templateList;

	private transient Map<Integer, ItemTemplate> map_templateList;

	@Override
	public void reload() {

		try {
			String jsonStr = Files.toString(new File("data/item.json"), Charset.forName("UTF-8"));
			ObjectMapper mapper = new ObjectMapper();
			templateList = mapper.readValue(jsonStr, new TypeReference<List<ItemTemplate>>() {
			});
			logger.info("size={}", templateList.size());
			Map<Integer, ItemTemplate> tmpmap = new HashMap<>();
			for (ItemTemplate itemTemplate : templateList) {
				tmpmap.put(itemTemplate.getItemid(), itemTemplate);
			}
			map_templateList = tmpmap;
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public boolean isTemplateExit(int item_id) {
		return map_templateList.containsKey(item_id);

	}

	public static void main(String[] args) {
		new ItemTemplateCache().reload();
	}

}